/**
 * Abstract class for all Chisame activity.
 */

package in.abip.chisame;

import in.abip.chisame.model.DatabaseHelper;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;

/**
 * Main activity for Chisame. All other activity should extend this class.
 * 
 * @author Julot.
 * @since Thursday, January 20th, 2011.
 */
public abstract class ChisameActivity extends Activity {
	// private static final String TAG = ChisameActivity.class.getName();

	// public ChisameApplication getApp() {
	// return (ChisameApplication) this.getApplication();
	// }
	//
	// @Override
	// public void onUserInteraction() {
	// super.onUserInteraction();
	// getApp().touch();
	// }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.settings, menu);
		menu.findItem(R.id.settings).setIntent(
				new Intent(this, SettingsActivity.class));
		menu.findItem(R.id.camera).setIntent(
				new Intent(this, CameraFormActivity.class));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		String menu = item.getTitle().toString();
		if (menu.equals(getString(R.string.download))) {
			downloadDb();
		} else {
			super.onOptionsItemSelected(item);
			startActivity(item.getIntent());
		}
		return true;
	}

	/**
	 * Download database from server. If we didn't use http server again, we
	 * won't need this method anymore.
	 */
	private void downloadDb() {
		String server = "192.168.0.1";
		SharedPreferences pref = getSharedPreferences(SettingsActivity.HARDWARE,
				Context.MODE_PRIVATE);
		if (pref.contains(SettingsActivity.HARDWARE)) {
			server = (pref.getString(SettingsActivity.IP, "192.168.0.1"));
		}
		DatabaseHelper dbHelper = new DatabaseHelper(this);
		// Release
		String url = "http://" + server + "/index.php?r=site/download";
		// Development
		// String url = (
		// "http://" + server + "/Negima/Haruna/index-dev.php?r=site/download"
		// );
		dbHelper.downloadDataBase(url);
		populate();
		refresh();
	}

	/**
	 * Populate page with content.
	 */
	protected void populate() {
	}

	/**
	 * Refresh page content with current value from server.
	 */
	protected void refresh() {
	}
}
